/**
 * @Title: LotteryRecordImpl
 * @Package cn.com.yiqi.wsc.service.lottery.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-林威
 * @date 2017/2/20 16:43
 * @version V1.0
 */
package cn.com.yiqi.wsc.service.lottery.impl;

import cn.com.yiqi.wsc.Ro.LotterRecordVO;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.customer.CustomerPrivilegeMapper;
import cn.com.yiqi.wsc.dao.customer.RankMapper;
import cn.com.yiqi.wsc.dao.lottery.LotteryActivityMapper;
import cn.com.yiqi.wsc.dao.lottery.LotteryActivityTicketMapper;
import cn.com.yiqi.wsc.dao.lottery.LotteryItemsMapper;
import cn.com.yiqi.wsc.dao.lottery.LotteryRecordMapper;
import cn.com.yiqi.wsc.entity.lottery.*;
import cn.com.yiqi.wsc.entity.shop.Item;
import cn.com.yiqi.wsc.service.customer.CustomerService;
import cn.com.yiqi.wsc.service.item.ItemService;
import cn.com.yiqi.wsc.service.lottery.enumerate.ActivityStatus;
import cn.com.yiqi.wsc.service.lottery.enumerate.ActivityTypeEnum;
import cn.com.yiqi.wsc.service.lottery.enumerate.LotteryItemTypeEnum;
import cn.com.yiqi.wsc.service.lottery.enumerate.LotteryRecordStatus;
import cn.com.yiqi.wsc.service.order.impl.OrderServiceImpl;
import cn.com.yiqi.wsc.service.point.PointService;
import cn.com.yiqi.wsc.service.point.dataobject.PointOrderDO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 会员系统组-林威
 * @ClassName: LotteryRecordImpl
 * Description: TODO
 * @date 2017/2/20 16:43
 */
@Service
public class LotteryRecordImpl {

    @Autowired
    LotteryRecordMapper recordDao;

    @Autowired
    LotteryActivityMapper activityDao;

    @Autowired
    LotteryActivityTicketMapper ticketDao;

    @Autowired
    RankMapper rankDao;

    @Autowired
    CustomerPrivilegeMapper privilegeDao;

    @Autowired
    LotteryItemsMapper itemDao;
    @Autowired
    CustomerService customerService;

    @Autowired
    PointService pointservice;

    @Autowired
    ItemService itemService;

    @Autowired
    OrderServiceImpl orderservice;
    @Autowired
    LotterServiceImpl lotterService;
    /**
     * 滚动中奖记录
     */
    public List<LotterRecordVO> findPrizes(Integer total,Integer activityId) {

        return recordDao.findRecordVo(total,1,null,1,activityId);
    }

    /**
     * 个人中奖记录
     */
    public PageInfo<LotterRecordVO> lotteryrecord(Integer userId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        return new PageInfo<LotterRecordVO>(recordDao.findRecordVo(null,null,userId,null,null));
    }

    /**
     * 计算今天使用次数
     */
    public Integer findUseTimes(Integer userId, int i) {

        return recordDao.countTimes(userId, i);
    }

    /**
     * 计算历史使用次数
     */
    public Integer findUseTimesAll(Integer userId,int activityId) {

        return recordDao.countByAllTime(userId,activityId);
    }


    /**
     * 还能否抽奖
     */
    @Transactional
    public Result draw(Integer userId,Integer activityId) {
        Result re = new Result();
        LotteryActivity activity = lotterService.findActivityById(activityId);
        if (activity == null) {
            ResultUtil.fail(re, "活动未开始或已关闭！");
            return re;
        }

        //参与条件，用户等级
//        if(activity.getLimitRankId() != null){
//            //查询该等级权重
//            Rank needRank = rankDao.selectByPrimaryKey(activity.getId());
//            //用户等级权重
//            Rank userRank = rankDao.findUserWeight(userId);
//            if(null != needRank){
//                if(null == userRank ||  userRank.getWeight() < needRank.getWeight()){
//                    ResultUtil.fail(re,"等级不够，需要"+needRank.getName()+"才可抽奖!当前等级"+userRank.getName());
//                    return re;
//                }
//            }
//        }
//2017 .4.5 不限制总次数
        Integer activityTime = activity.getTimesDay();
        //总计参与次数
        Integer totalJoin = findUseTimesAll(userId,activityId);

        //一人只能参与一次
        if (activityTime == -1) {
            if (totalJoin > 0) {
                ResultUtil.fail(re, "已经参与过该活动，只能参与一次！");
                return re;
            }
        }


        //今天已经抽了次数
         Integer userTimes = findUseTimes(userId, activity.getId());
        if (userTimes >= activityTime) {
            ResultUtil.fail(re, "今天次数已用完！");
            return re;
        }

        //积分购买的次数 和 分享得到次数
        Long remainTimes = ticketDao.sumUserTimes(userId,activity.getId());

        //每天免费次数 2017-4-5 总免费次数
        Integer freeTimes = activity.getFreeTime();

        //免费次数剩余
        Long freeLeft = remainTimes + freeTimes - totalJoin;

        // Long hasShare = ticketDao.hasShare(userId);
        if (freeLeft > 0) {
            re = doDraw(userId, activity);
            return ResultUtil.success(re);
        } else {
            //可购买
            activity.init();
            if(null != activity.getCostPointToBuy()){
                re.putData("canBuy", true);
                re.putData("cost", activity.getCostPointToBuy());
                re.putData("buyTimes", activity.getBuyTimes());
            }
            return ResultUtil.fail(re, "次数已用完！");
        }
    }

    /**
     * 抽奖
     */
    private Result doDraw(Integer userId, LotteryActivity activity) {
        Result re = new Result();
        List<LotteryItems> list = itemDao.findLotterys(activity.getId());
        Integer maxWeight = 0;
        for (LotteryItems items : list) {
            maxWeight += Integer.parseInt(items.getWinRate() + "");
        }
        Integer temp = RandomUtils.nextInt(0, maxWeight);
        Integer n = 0;
        Integer m = list.get(0).getWinRate() * 1;
        for (int i = 0; i < list.size() - 1; i++) {
            if (temp >= n && temp < m) {
                //抽中奖品
                LotteryRecord record = new LotteryRecord();
                LotteryItems item = list.get(i);
                Integer type = Integer.parseInt(item.getType()+"");
                //礼品类型 1积分 2商品 3未中奖
                if (type == LotteryItemTypeEnum.thankyou.getValue()) {
                    //抽中谢谢参与
                    record.setWin(Byte.parseByte("0"));
                    record.setStatus(LotteryRecordStatus.hasget.getValue());
                } else {
                    record.setWin(Byte.parseByte("1"));
                    if (type == LotteryItemTypeEnum.point.getValue()) {
                        //送积分 直接领取
                        record.setStatus(LotteryRecordStatus.hasget.getValue());
                        PointOrderDO pdo = new PointOrderDO();
                        pdo.setCustomerId(Long.parseLong(userId + ""));
                        pdo.setPoint(Integer.parseInt(item.getContent()));
                        pointservice.lotteryGetPoint(pdo);
                    } else{
                        record.setStatus(LotteryRecordStatus.notget.getValue());
                    }
                }
                /**若果不是抽中谢谢参与 奖品数量减一*/
                if (type != LotteryItemTypeEnum.thankyou.getValue()) {
                    item.setCount(item.getCount()==null?0:item.getCount()==0?0:item.getCount() - 1);
                    itemDao.updateByPrimaryKeySelective(item);
                }
                record.setCustomerId(userId);
                record.setActivityId(activity.getId());
                record.setLotteryItemId(item.getId());
                record.setJoinTime(new Date());
                recordDao.insertSelective(record);
                re.putData("goGet",(type == LotteryItemTypeEnum.goods.getValue() ? true: false));
                re.putData("lotteryName", item.getName());
                re.putData("lotteryId", item.getId());
                re.putData("recordId",record.getId());
                break;
            }
            n = n + list.get(i).getWinRate();
            m = m + list.get(i + 1).getWinRate();
        }
        return re;
    }

    /**
     * 大转盘积分买次数
     */
    public Result buyTime(Integer userId,Integer activityId) {
        Result re = new Result();
        LotteryActivity activity = activityDao.findById(activityId);
        activity.init();
        if (activity == null) {
            ResultUtil.fail(re, "活动未开始或已关闭！");
            return re;
        }
        Integer userPoint = customerService.selectById(userId).getPoint();
        Integer costPoint = activity.getCostPointToBuy();
        if (null == costPoint) {
            ResultUtil.fail(re, "不可购买");
            return re;
        }
        if (userPoint < costPoint) {
            ResultUtil.fail(re, "剩余积分不足，当前积分" + userPoint);
            return re;
        }

        //TODO 扣除积分
        PointOrderDO pointDo = new PointOrderDO();
        pointDo.setCustomerId(Long.parseLong(userId + ""));
        pointDo.setPoint(costPoint);
        pointDo.setTime(new Date());
        Long pointRecordId = pointservice.lotteryUsePoint(pointDo).getReturnValue();
        //TODO 增加抽奖次数
        LotteryActivityTicket tiket = new LotteryActivityTicket();
        tiket.setActivityId(activity.getId());
        tiket.setCustomerId(userId);
        tiket.setGetTime(new Date());
        tiket.setPointRecordId(pointRecordId.intValue());
        tiket.setTimes(activity.getBuyTimes());
        tiket.setGetType(Byte.parseByte("2"));//1分享 2积分兑换
        ticketDao.insertSelective(tiket);
        return ResultUtil.success(re);
    }

    /**
     * 领奖
     */
    @Transactional
    public Result getLottery(Integer id, Integer userId, Integer addressId) {
        Result re = new Result();
        LotteryRecord record = recordDao.findByIdAndUserId(id, userId);
        if (record == null || record.getStatus() == LotteryRecordStatus.hasget.getValue() || record.getWin() == 0) {
            return ResultUtil.fail(re, "奖品不存在或已领取！");
        }
        LotteryItems lottery = itemDao.selectByPrimaryKey(record.getLotteryItemId());
        Integer itemId = Integer.parseInt(lottery.getContent());
        Item item = itemService.findByid(itemId);
        if (item != null) {
            orderservice.createLotteryOrder(item, userId, addressId);
            record.setStatus(LotteryRecordStatus.hasget.getValue());
            recordDao.updateByPrimaryKeySelective(record);
            return ResultUtil.success(re);
        } else {
            return ResultUtil.fail(re, "奖品不存在！");
        }
    }
}
